var express = require("express")
var router = express.Router()
var QcloudSms = require("qcloudsms_js")
var connection = require("../../../db/sql")
var jwt = require("jsonwebtoken")
const bcrypt = require("bcryptjs")
var alipaySdk = require("./alipay")
var AlipayFormData = require("alipay-sdk/lib/form").default
// import axios from "axios"
const paySql = require("./paySql")
var axios = require("axios")

// 发起支付
router.post("/api/pay/payment", function (req, res, next) {
  // 前端传的参数
  let params = req.body

  // 开始对接支付宝API
  const formData = new AlipayFormData()
  formData.setMethod("get")
  // 支付时的信息
  formData.addField("bizContent", {
    outTradeNo: params.id, //订单号
    productCode: "FAST_INSTANT_TRADE_PAY",
    totalAmount: params.price, //总价格
    subject: "校园商城", //商品名称
    body: "", //商品描述
  })

  // 支付成功失败跳转的连接
  formData.addField("returnUrl", "http://localhost:8080/paysuccess")
  // 返回promise
  const reslut = alipaySdk.exec(
    "alipay.trade.page.pay",
    {},
    { formData: formData }
  )

  reslut.then((resp) => {
    res.send({
      data: {
        code: 200,
        success: true,
        msg: "支付中",
        paymentUrl: resp,
      },
    })
  })
})

// 判断支付结果
router.post("/api/pay/payreslut", function (req, res, next) {
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  let params = req.body
  let out_trade_no = params.out_trade_no
  let trade_no = params.trade_no
  console.log(params)

  // 开始对接支付宝API
  const formData = new AlipayFormData()
  formData.setMethod("get")
  // 支付时的信息
  formData.addField("bizContent", {
    out_trade_no,
    trade_no,
  })

  const reslut = alipaySdk.exec(
    "alipay.trade.query",
    {},
    { formData: formData }
  )

  // 后端请求支付宝
  reslut.then((ressData) => {
    axios({
      method: "GET",
      url: ressData,
    })
      .then((data) => {
        console.log(data)
        let responseCode = data.data.alipay_trade_query_response
        if (responseCode.code == "10000") {
          switch (responseCode.trade_status) {
            case "WAIT_BUYER_PAY":
              res.send({
                data: {
                  code: 0,
                  msg: "支付宝有交易，没付款",
                },
              })
            case "TRADE_CLOSED":
              res.send({
                data: {
                  code: 1,
                  msg: "交易关闭",
                },
              })

            case "TRADE_FINISHED":
              res.send({
                data: {
                  code: 2,
                  msg: "交易成功,不可退款",
                },
              })

            case "TRADE_SUCCESS":
              /*支付成功以后，修改订单的状态*/
              // 1查询订单号的id
              connection.query(
                paySql.selectOrderId(out_trade_no),
                function (err, reslut) {
                  if (err) {
                    res.send({
                      code: 201,
                      msg: "查询订单号出错",
                      err,
                    })
                  }
                  console.log(reslut)

                  connection.query(
                    paySql.updateOrderStatus(reslut[0].id),
                    function (errs, resluts) {
                      if (errs) {
                        res.send({
                          code: 201,
                          msg: "更新订单号出错",
                          errs,
                        })
                      }

                      res.send({
                        code: 200,
                        msg: "交易成功，更新订单号状态成功",
                        data: resluts,
                      })
                    }
                  )
                }
              )
            // res.send({
            //   data: {
            //     code: 3,
            //     msg: "交易完成，可退款",
            //   },
            // })
          }
        } else if (responseCode.code == "40004") {
          res.send({
            data: {
              code: 4,
              msg: "交易不存在",
            },
          })
        }
      })
      .catch((err) => {
        res.send({
          data: {
            code: 500,
            msg: "交易失败",
            err,
          },
        })
      })
  })
})

module.exports = router
